﻿using Newtonsoft.Json;
using QuickPasteToolWeb.Helper;
using QuickPasteToolWeb.Infrastructure;
using QuickPasteToolWeb.Model;
using System.Configuration;
using System.IO;

namespace QuickPasteToolWeb.Service
{
    public class FileOperationService : IFileOperationService
    {
        private static  string _folderPath => SettingHelper.GetFolder();

        public IEnumerable<Content> QueryFile(string query)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(_folderPath);
            FileInfo[] files = directoryInfo.GetFiles();
            var contents = new List<Content>();
            foreach (FileInfo file in files)
            {
                var fileData = File.ReadAllText(file.FullName);
                if (!string.IsNullOrEmpty(fileData) && fileData.Contains(query))
                {
                    contents.Add(JsonConvert.DeserializeObject<Content>(fileData));
                }
            }
            if (contents.Any())
            {
                return contents.OrderByDescending(t => t.ModifyTime).ToList();
            }
            return new List<Content>();
        }

        public void ReadFile(string path)
        {
            throw new NotImplementedException();
        }

        public void SaveFile(string fileStr)
        {
            var content = new Content
            {
                ContentDetail = fileStr
            };
            var fileName = $"{content.Id}.json";
            File.WriteAllText($"{_folderPath}\\{fileName}", JsonConvert.SerializeObject(content));
        }
    }
}
